// @flow
import React, { Component } from 'react'
import { message, Button } from 'antd'
import DeviceTypeBrowser from 'components/DeviceTypeBrowser'
import styles from './Home.css'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
type Props = {
  history: Array<any>
}

type States = {
  data: Array<any>,
  specs: Array<any>,
  types: Array<any>,
  visible: boolean,
  datas: Array<any>,
  rowData: Array<Object>,
  total: number,
  current: number,
  pageSize: number
}
class DeviceType extends Component {
  props: Props
  state: States
  getDevices: Function
  getDevicesFresh: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      parentId: '',
      data: [],
      specs: [],
      types: [],
      rowData: [],
      visible: false,
      datas: [],
      total: 0,
      current: 1,
      pageSize: 20
    }
    this.getDevices = this.getDevices.bind(this)
    this.getDevicesFresh = this.getDevicesFresh.bind(this)
  }
  componentWillMount () {
    this.getDevices(this.state.current, this.state.pageSize)
  }

  getDevicesFresh () {
    this.getDevices(this.state.current, this.state.pageSize)
  }

  getDevices (page: number, pageSize: number) {
    universalFetch(`${__SERVICE_API__}device/templates/devices?pageNum=${page}&pageSize=${pageSize}&type=deep`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          current: page,
          total: json.pageInfo.total,
          rowData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  handleCancel = () => {
    this.setState({
      visible: false
    })
  }

  handleDelete = (record: Object) => {
    universalFetch(`${__SERVICE_API__}device/templates/devices/${record.id}`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      method: 'DELETE'
    })
    .then(() => {
      this.getDevices(this.state.current, this.state.pageSize)
      message.info('删除成功')
    })
    .catch((error) => {
      console.error(error)
      message.info('删除失败')
    })
  }

  render () {
    const { rowData, current, pageSize, total } = this.state
    return (
      <div className={styles['main']}>
        <Button type='primary' style={{ marginLeft: '10px' }}
          onClick={() => this.props.history.push('/business/device-type-add')}>添加设备模板</Button>
        <DeviceTypeBrowser {...{
          current,
          pageSize,
          total,
          rowData,
          refreshMaintenances: this.getDevices,
          history: this.props.history,
          refreshView: this.getDevicesFresh,
          deleteDevice: this.handleDelete
        }} />
      </div>
    )
  }
}

export default DeviceType
